Repository navigation
Jpeg: true streaming decode from forward-only streams - #16
Merged
Merged
Conversation
JpegImageDecoder implements IStreamingImageDecoder (Registration.CreateRowReader), plus OpenRowReader / OpenRowReaderAsync over a Stream. A sequential frame whose first scan interleaves every component is decoded as it arrives, MCU row by MCU row, with the existing two-MCU-row strips; rows go to the caller's band and the rest stay pending in the strips. Each MCU row (and each marker step after the scan) is a unit: the entropy state is checkpointed before it and rolled back when it read past the buffered input and the stream has not ended, so the rows equal TryDecodeInto's byte for byte. DCT-domain scales 2/4/8 stream too; progressive, multi-scan, region, orientation and larger scales take the buffered fallback. The span decode keeps its arithmetic and sequence: reads past the data now also set an overrun flag, EmitRows stops at a row limit (OutY for a whole decode), and the streaming scan's per-MCU-row body is factored out. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…g the next A row started near the end of the buffered input is usually undone and decoded again; waiting for about one row's worth of input first avoids the wasted work. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
JpegImageDecoderimplementsIStreamingImageDecoder;Registration.CreateRowReaderis set by method group. New publicOpenRowReader(Stream, PixelFormat, DecodeOptions?, bool leaveOpen)andOpenRowReaderAsync(...)(PublicAPI.Unshipped.txt updated).JpegRowReader(new, internal) drivesJpegCoreoverStreamInput.Buffered. A sequential frame whose first scan interleaves every component streams MCU row by MCU row through the existing two-MCU-row strips. DCT-domain scales 2/4/8 stream too. Progressive, multi-scan, no-scan frames,Region,ApplyOrientationand scales above 8 useUseBufferedFallback(IsStreaming == false).JpegCore.Suspendedbetween calls. Each MCU row, and each marker step after the scan, is one unit. Before a unit the code checkpoints the bit buffer and count, position, DC predictors, restart counter, EOB run, marker and nomore state. If the unit read past the buffered window and the stream has not ended, it rolls back and returns NeedMoreData. Reads past the window are detected by a new_overrunflag set inGet8/Skip/AtEnd. The 8-byte fast refill already stops at_data.Length - 8, so it never reads past the window. Once the stream has ended, reads past the end are the same zeros a whole decode reads, so salvage and truncation behaviour matchTryDecodeIntoexactly. The last row is held back until the trailing markers are parsed.EmitRowsstops at_emitLimit(which isOutYfor the span decode), and rows not yet asked for stay pending in the strips._overrunbookkeeping, the_emitLimit/_destY0row offset, and the per-MCU-row body ofDecodeStreamingScanfactored out. Nothing touchesJpegIdct,JpegResampleorJpegColor.JpegCoreis nowpartial; its instance fields stay inJpegCore.cs. A reflection test makes sure every field has a namesake inSuspended.AbBenchmarks.Streaming(16-row bands from aMemoryStream). Before timing it checks that its output equalsDecodeTobyte for byte, and the result table gains astreaming ÷ currentcolumn.Tests
JpegStreamingDecodeTests:JpegDecoderOracleTestscase (all subsamplings, gray, CMYK/YCCK, restarts, non-interleaved, progressive, truncated salvage) × 8 PixelFormats (incl. Gray8, GrayAlpha16, Rgba64, premultiplied) × everyStreamingAssertfeed, plus 1/2 scale. Encoder variants (restart 1/7, optimized Huffman, gray, 16×16, 67×1, 4:2:2, 4:1:1) at 1/1, 1/4 and 1/8.Info.InvalidDataException, exactly whereTryDecodeIntofails.FileStreamwrapped async-only throughOpenRowReaderAsync/ReadRowsAsync.JpegFuzzTests.MutatedStreams_StreamingMatchesDecodeInto: the reader must matchTryDecodeIntoexactly when it succeeds and throwInvalidDataExceptionwhen it fails, over random scales, formats and feeds. Iterations come fromJPEG_STREAM_FUZZ_ITERATIONS, falling back toJPEG_FUZZ_ITERATIONS.DOTNET_EnableAVX2=0andDOTNET_EnableHWIntrinsic=0runs of the JPEG classes pass. No new warnings. Goldens untouched.Soaks (both ran clean at 300000):
Perf (AMD Ryzen 7 5800X, Windows 11 26200, .NET 10.0.15, AVX2, no AVX-512;
baseline 533b03e+ab, run from a worktree outside the repo)Geomean over the quick subset: span decode current ÷ baseline 0.98×, streaming ÷ current 1.03×. The progressive file is the buffered fallback and comes out at 1.19×. The machine was shared with other agents, so single files swing ±10% between runs. In an earlier run, before streaming waited for about 1.5× the previous MCU row's bytes before starting the next row, streaming was 1.08×.
Needs outside this unit
JPEG_STREAM_FUZZ_ITERATIONS(it followsJPEG_FUZZ_ITERATIONSwhen unset, so the existing command already soaks it).StreamingRowReaderhas no way to pass the caller'sCancellationTokeninto the codec step. The JPEG reader therefore writes at most 256 rows perDecodeRowscall, so the driver checks the token between calls.🤖 Generated with Claude Code